using System;
using System.Collections.Generic;
using WegasManagementSystem.DAL;
using WegasManagementSystem.Models;

namespace WegasManagementSystem.BLL
{
    /// <summary>
    /// 部门业务逻辑类
    /// </summary>
    public class DepartmentBLL
    {
        private DepartmentDAL departmentDAL;

        /// <summary>
        /// 构造函数
        /// </summary>
        public DepartmentBLL()
        {
            departmentDAL = new DepartmentDAL();
        }

        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="department">部门对象</param>
        /// <returns>新部门ID，失败返回0</returns>
        public int AddDepartment(Department department)
        {
            if (department == null)
                throw new ArgumentNullException("department", "部门对象不能为空");

            if (string.IsNullOrEmpty(department.DeptName))
                throw new ArgumentException("部门名称不能为空");

            if (string.IsNullOrEmpty(department.DeptCode))
                throw new ArgumentException("部门编码不能为空");

            // 检查部门编码是否已存在
            if (departmentDAL.CheckDeptCodeExists(department.DeptCode))
                throw new Exception("部门编码已存在");

            // 检查上级部门是否存在
            if (department.ParentId.HasValue && department.ParentId.Value > 0)
            {
                Department parentDept = departmentDAL.GetDepartmentById(department.ParentId.Value);
                if (parentDept == null)
                    throw new Exception("上级部门不存在");
            }

            return departmentDAL.AddDepartment(department);
        }

        /// <summary>
        /// 更新部门信息
        /// </summary>
        /// <param name="department">部门对象</param>
        /// <returns>更新成功返回true，失败返回false</returns>
        public bool UpdateDepartment(Department department)
        {
            if (department == null)
                throw new ArgumentNullException("department", "部门对象不能为空");

            if (string.IsNullOrEmpty(department.DeptName))
                throw new ArgumentException("部门名称不能为空");

            if (string.IsNullOrEmpty(department.DeptCode))
                throw new ArgumentException("部门编码不能为空");

            // 检查部门编码是否已存在（排除当前部门）
            if (departmentDAL.CheckDeptCodeExists(department.DeptCode, department.DeptId))
                throw new Exception("部门编码已存在");

            // 检查是否形成循环依赖
            if (department.ParentId.HasValue && department.ParentId.Value > 0)
            {
                if (department.ParentId.Value == department.DeptId)
                    throw new Exception("部门的上级部门不能是自己");

                // 检查是否将部门设为自己的子部门的子部门
                List<Department> allDepartments = departmentDAL.GetAllDepartments();
                CheckCircularDependency(allDepartments, department.DeptId, department.ParentId.Value);
            }

            return departmentDAL.UpdateDepartment(department);
        }

        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="deptId">部门ID</param>
        /// <returns>删除成功返回true，失败返回false</returns>
        public bool DeleteDepartment(int deptId)
        {
            if (deptId <= 0)
                throw new ArgumentException("无效的部门ID");

            return departmentDAL.DeleteDepartment(deptId);
        }

        /// <summary>
        /// 获取所有部门
        /// </summary>
        /// <returns>部门列表</returns>
        public List<Department> GetAllDepartments()
        {
            return departmentDAL.GetAllDepartments();
        }

        /// <summary>
        /// 获取部门树形结构
        /// </summary>
        /// <returns>顶级部门列表（包含子部门）</returns>
        public List<Department> GetDepartmentTree()
        {
            return departmentDAL.GetDepartmentTree();
        }

        /// <summary>
        /// 根据ID获取部门
        /// </summary>
        /// <param name="deptId">部门ID</param>
        /// <returns>部门对象</returns>
        public Department GetDepartmentById(int deptId)
        {
            if (deptId <= 0)
                throw new ArgumentException("无效的部门ID");

            return departmentDAL.GetDepartmentById(deptId);
        }

        /// <summary>
        /// 检查循环依赖
        /// </summary>
        /// <param name="departments">所有部门</param>
        /// <param name="deptId">当前部门ID</param>
        /// <param name="parentId">要设置的上级部门ID</param>
        private void CheckCircularDependency(List<Department> departments, int deptId, int parentId)
        {
            Department parentDept = departments.Find(d => d.DeptId == parentId);
            if (parentDept == null)
                return;

            if (parentDept.ParentId.HasValue && parentDept.ParentId.Value > 0)
            {
                if (parentDept.ParentId.Value == deptId)
                    throw new Exception("不能将部门设为其子部门的子部门，会形成循环依赖");

                // 递归检查
                CheckCircularDependency(departments, deptId, parentDept.ParentId.Value);
            }
        }
    }
} 